using System.Net.Http.Json;
using APITransLib.Contracts;
using ChatWithMultAI.ViewModels.Agent;
using Microsoft.Maui.Devices;
using Microsoft.Maui.Storage;

namespace ChatWithMultAI.Services;

/// <summary>
/// 客户端应用配置/启动辅助：
/// - 选择服务端 BaseAddress（本地/模拟器）
/// - 首次启动自动创建用户并保存到 Preferences
/// - 保证静态智能体 <see cref="AgentHost"/> 已初始化
/// </summary>
public static class AppConfig
{
    private const string PrefUserId = "app.user.id";
    private const string PrefUserName = "app.user.name";

    /// <summary>
    /// 获取服务端基础地址。Android 模拟器需通过 10.0.2.2 访问宿主机。
    /// </summary>
    public static string GetBaseAddress()
    {
        var isAndroid = DeviceInfo.Platform == DevicePlatform.Android;
        return isAndroid ? "http://10.0.2.2:5000" : "http://localhost:5000";
    }

    /// <summary>
    /// 首次启动初始化：创建/查询用户，并启动静态智能体。
    /// </summary>
    public static async Task InitializeAsync(string? baseAddress = null, CancellationToken ct = default)
    {
        baseAddress ??= GetBaseAddress();
        var http = new HttpClient { BaseAddress = new Uri(baseAddress) };

        var userId = Preferences.Get(PrefUserId, null);
        var userName = Preferences.Get(PrefUserName, null);
        if (string.IsNullOrEmpty(userId))
        {
            userName = $"User-{Guid.NewGuid().ToString("N")[..6]}";
            var created = await CreateUserAsync(http, userName, ct);
            userId = created.Id;
            Preferences.Set(PrefUserId, userId);
            Preferences.Set(PrefUserName, created.DisplayName);
        }

        await AgentHost.EnsureStartedAsync(userId!, baseAddress);
    }

    /// <summary>
    /// 向服务端创建一个新用户。
    /// </summary>
    private static async Task<UserDto> CreateUserAsync(HttpClient http, string displayName, CancellationToken ct)
    {
        var res = await http.PostAsJsonAsync("api/users", new CreateUserRequest { DisplayName = displayName }, ct);
        res.EnsureSuccessStatusCode();
        var body = await res.Content.ReadFromJsonAsync<CreateUserResponse>(cancellationToken: ct);
        if (body?.User is null) throw new InvalidOperationException("Create user failed");
        return body.User;
    }
}
